<?php

class GXRSS extends GXModule {

	// the System config
	private $config = null;

	/**
	 * __construct
	 * @param object $config	// passed by GXModule
	 * @return boolean
	 */
	public function __construct( $config = null ){
		parent::__construct();

		// if we don't have a config, grab it from System
		if( !$config ){
			$config = $this->SystemConfig->xpath('//Modules/RSS',0);
		}

		// store this config
		$this->config = $config->exec->get(GXDOM::AS_GXDOM);

		// set the config
		$this->config = $config;

		// return boolean
		return true;
	}

	/**
	 * show
	 *
	 * Builds an RSS2.0 compliant xml document. Only RSS2.0 is supported right now.
	 * http://www.rssboard.org/rss-specification
	 * @param string $name the name of the channel as defined in System.xml
	 * @param array $items a numerically-indexed array of items to include in the feed
	 * @return object GXDOM or false on failure
	 */
	public function show( $name = null, $items = null ){
		if( !$name ){
			trigger_error( 'Missing the name of the feed', E_USER_ERROR );
			return false;
		}

		// get the named feed config
		$feedconfig = simplexml_import_dom( clone $this->config->exec->xpath($name,0)->node );
		if( !$feedconfig ){
			trigger_error( 'Unable to locate a channel by that name (' .$name .')', E_USER_ERROR );
			return false;
		}

		// check for @format and warn we only support RSS2
		if( $feedconfig['format'] ){
			trigger_error( 'Note: GXRSS supports RSS2 format only at this time', E_USER_WARNING );
		}

		// build the header
		$feed = new GXDOM( 'rss', null, array('version'=>'2.0') );
		$channel = $feed->channel();
		foreach( $feedconfig as $key => $val ){
			$channel->$key( strval($val) );
		}
		// if we have items, add them
		if( $items ){
			foreach( $items as $itm ){
				$i = $channel->item();
				foreach( $itm as $key => $val ){
					$i->$key( $val, ( ($key == 'guid') ? array('isPermaLink'=>'false') : null ) );
				}
			}
		}

		// return the entire feed
		return $feed;
	}

}
?>